﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XTYAPI.通讯
{
   public class UDPClient
    {
        private Socket udpClient;
        // 一次正常的交互的互斥锁
        private SimpleHybirdLock InteractiveLock = new SimpleHybirdLock();
        /// <summary>
        /// 等待时间单位10ms
        /// </summary>
        public int WaitTimes { get; private set; } = 5;
        public UDPClient()
        {
            udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
            udpClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
        }    
        public byte[] Send(byte[] SendByte,string ip,int port)
        {
            try
            {
                IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                udpClient.SendTo(SendByte, SendByte.Length, SocketFlags.None, iPEndPoint);
                int k = udpClient.Available;
                int timer = 0;
                while (k == 0)
                {
                    timer++;
                    k = udpClient.Available;
                    Thread.Sleep(10);
                    if (timer > WaitTimes)
                        break;
                }
                byte[] myBufferBytes = new byte[k];
                IPEndPoint iPEnd = new IPEndPoint(IPAddress.Any,0);
                EndPoint endPoint = iPEnd;
                udpClient.ReceiveFrom(myBufferBytes, ref endPoint);
                return myBufferBytes;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                InteractiveLock.Leave();
            }
        }
    }
}
